package com.itheima.chanlin.scheduling;


import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;

@Component
public class SqlScheduling {
    /**
     * 每天18点25分执行备份
     */
    @Scheduled(cron = "0 2 19 ? * *")
    public void sqldemo(){
        try {
            String comman = "mysqldump -uroot -h 43.143.49.28 -P 3333 -p5d4e1a406d4a9 chanlin";

            Date date = new Date();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");

            String fPath="/chanlinData/"+simpleDateFormat.format(date)+".sql";
            Runtime rt = Runtime.getRuntime();
            Process child = rt.exec(comman);
            InputStream in = child.getInputStream();

            OutputStream out = new FileOutputStream(new File(fPath));

            byte[] bytes = new byte[1024];
            int len = -1;

            while ((len = in.read(bytes)) != -1) {
                out.write(bytes,0,len);
                out.flush();
            }
            out.close();
            in.close();

            System.out.println(simpleDateFormat.format(date)+"数据库chanlin备份成功");
        } catch (IOException e) {
            System.out.println(new Date()+"数据库chanlin备份失败");
            e.printStackTrace();
        }
    }

    public void sqldemo2(){
        try {
            String comman = "mysqldump -uroot -h 43.143.49.28 -P 3333 -p5d4e1a406d4a9 chanlin";

            Date date = new Date();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");

            String fPath="d:/"+simpleDateFormat.format(date)+".sql";
            Runtime rt = Runtime.getRuntime();
            Process child = rt.exec(comman);
            InputStream in = child.getInputStream();

            OutputStream out = new FileOutputStream(new File(fPath));

            byte[] bytes = new byte[1024];
            int len = -1;

            while ((len = in.read(bytes)) != -1) {
                out.write(bytes,0,len);
                out.flush();
            }
            out.close();
            in.close();

            System.out.println(simpleDateFormat.format(date)+"数据库chanlin备份成功");
        } catch (IOException e) {
            System.out.println(new Date()+"数据库chanlin备份失败");
            e.printStackTrace();
        }
    }
}
